const { ipcMain, dialog } = require('electron');
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');

const tmpPath = path.join(__dirname, './build/static/tmp');

// 清空tmp缓存目录
function clearTmpDir(tmpPath) {
    if (fs.existsSync(tmpPath)) {
        const tmpDirs = fs.readdirSync(tmpPath, {
            withFileTypes: true
        });
        tmpDirs.forEach(dirent => {
            if (dirent.isFile()) {
                fs.unlinkSync(path.join(tmpPath, dirent.name));
            }
        });
    } else {
        fs.mkdirSync(tmpPath);
    }
}

// 创建二维码
function createQrCode(pathArr, wxPlatform) {
    return new Promise((resolve, reject) => {
        if (!Array.isArray(pathArr) || pathArr.length === 0) {
            return reject(new Error('path is undefined'));
        };

        clearTmpDir(tmpPath);

        const cli = process.platform === 'darwin' ? 'qrcode' : 'qrcode.exe';

        let args = [];
        switch (wxPlatform) {
            case 'cd': 
            case 'hz':
            case 'nj':
                args = ['--platform', wxPlatform, '--base', tmpPath, '--path', pathArr.join(';')]
                break;
            default:
                args = ['--all', '--base', tmpPath, '--path', pathArr.join(';')]
        }

        childProcess.execFile(path.join(__dirname, `./bin/${cli}`), args, {encoding: 'utf-8'}, (err, stdout, stderr) => {
            if (err || stderr) {
                return reject(new Error(err));
            } else {
                resolve(stdout.split(','));
                
            }
        });
    });
}

/**
 * 创建二维码接口 <ipc>
 * @param {Object} event ipc句柄
 * @param {any} arg ipc传递的参数
 */
ipcMain.on('create-qrcode-message', (event, arg) => {
    createQrCode(arg.path, arg.platform)
        .then(stdout => {
            event.reply('create-qrcode-reply', stdout);
        })
        .catch(() => {
            event.reply('create-qrcode-reply', false);
        });
});

/**
 * 选择文件夹 <ipc>
 * @param {Object} event ipc句柄
 * @param {any} arg ipc传递的参数
 */
ipcMain.on('open-directory-dialog-message', (event, arg) => {
    dialog.showOpenDialog({
        properties: ['openDirectory']
    })
        .then(result => {
            if (result.canceled) {
                event.reply('open-directory-dialog-reply', false);
            } else {
                event.reply('open-directory-dialog-reply', result.filePaths[0]);
            }
        })
        .catch(() => {
            event.reply('open-directory-dialog-reply', false);
        });
});

/**
 * 保存文件 <ipc>
 * @param {Object} event ipc句柄
 * @param {any} arg ipc传递的参数
 */
ipcMain.on('save-file-to-directory-message', (event, arg) => {
    if (!arg || !arg.from || !arg.to) return event.reply('save-file-to-directory-reply', false);

    if (!fs.existsSync(arg.to)) return event.reply('save-file-to-directory-reply', false);

    arg.from.forEach(file => {
        if (fs.existsSync(file)) {
            const parse = path.parse(file),
                toPath = `${arg.to}/${parse.base}`;
            fs.copyFileSync(file, toPath);
        }
    });

    event.reply('save-file-to-directory-reply', true);
});
